<template>
  <div :style="{ height: 100 }" class="container" ref="container">
    <BubbleList
      ref="listRef"
      :style="{ maxHeight: '300px', paddingInline: '16px' }"
      :roles="useRolesAsFunction ? rolesAsFunction : rolesAsObject"
      :items="messages"
    />
  </div>
</template>
<script setup lang="ts">
import { UserOutlined } from '@ant-design/icons-vue';
import { BubbleList } from 'ant-design-x-vue';
import type { BubbleProps,BubbleListProps } from 'ant-design-x-vue';
import { Typography,Avatar  } from 'ant-design-vue';
import markdownit from 'markdown-it';
import {  ref,  h, computed,watchEffect } from 'vue';
//pinia中拿到聊天消息
import { aiMessage } from '@/stores/aiMessage';


defineOptions({ name: 'AXBubbleMarkdownSetup' });

const rolesAsObject: BubbleListProps['roles'] = {
  ai: {
    placement: 'start',
    avatar: { icon: h(UserOutlined), style: { background: '#fde3cf' }},
    typing: { step: 5, interval: 20 },
    messageRender:"renderMarkdown",
    style: {
      maxWidth: '600px',
    },
  },
  user: {
    placement: 'end',
    avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
  },
};

const rolesAsFunction = (bubbleData: BubbleProps, index: number) => {
  const RenderIndex: BubbleProps['messageRender'] = (content) =>
    h(Flex, null, () => [h('text', null, `#${index}: ${content}`)]);
    switch (bubbleData.role) {
    case 'ai':
      return {
        placement: 'start' as const,
        avatar: { icon: h(UserOutlined), style: { background: '#fde3cf' } },
        typing: { step: 5, interval: 20 },
        style: {
          maxWidth: 600,
        },
        messageRender: RenderIndex,
      };
    case 'user':
      return {
        placement: 'end' as const,
        avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
        messageRender: RenderIndex,
      };
    default:
      return { messageRender: RenderIndex };
  }
   
};

const useRolesAsFunction = ref(false);

//使用计算函数来获取pinia中的消息
const messages = computed(() => {
  //数组长度没变，内容变了，不会触发更新
  return aiMessage().messages;
})

// 监听消息内容变化的更灵敏方式
const lastMessageContent = ref('')
watchEffect(() => {
  // 访问具体属性来建立响应式依赖
  if (messages.value.length > 0) {
    lastMessageContent.value = messages.value[messages.value.length - 1].content
  }
})

</script>

